package com.cnt.service.impl;

import com.cnt.dao.UserDao;
import com.cnt.dao.UserInfoDao;
import com.cnt.entity.User;
import com.cnt.entity.UserInfo;
import com.cnt.service.UserInfoService;
import com.cnt.util.LogUtil;
import com.cnt.vo.ResultVo;
import com.cnt.vo.UserResultVo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    //存储照片的相对路径
    private static final String IMAGE_DIR = "src/main/resources/static/image/";
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private LogUtil logUtil;

    public ResultVo<UserInfo> getUserInfo(Integer userId) {
        UserInfo userInfo = userInfoDao.selectByUserId(userId);
        if (userInfo == null) {
            return new ResultVo<>(1, "个人信息查询异常，请联系管理员", null);
        }
        return new ResultVo<>(0, "个人信息收集成功", userInfo);
    }

    public ResultVo<UserInfo> updateUserInfo(UserInfo userInfo) {
        UserInfo userInfoUpdate = userInfoDao.selectByUserId(userInfo.getUserId());
        User user = userDao.selectById(userInfo.getUserId());
        if (userInfoUpdate == null) {
            return new ResultVo<>(1, "提交失败，请联系管理员", null);
        }
        userInfo.setUserInfoId(userInfoUpdate.getUserInfoId());
        int i = userInfoDao.updateById(userInfo);
        if (i == 1) {
            logUtil.recordLog(user.getUserId(), user.getAccount() + "修改个人信息成功");
            return new ResultVo<>(0, "个人信息修改成功", null);
        }
        return new ResultVo<>(2, "系统繁忙，稍后再试", null);
    }


    public ResultVo<String> updateImage(Integer userId, MultipartFile file) {
        User user = userDao.selectById(userId);
        try {
            // 校验上传的文件类型
            String contentType = file.getContentType();
            System.out.println(contentType);
            if (!contentType.equals("image/jpeg") && !contentType.equals("image/png")) {
                logUtil.recordLog(user.getUserId(), user.getAccount() + "修改头像失败，因为不支持图片格式：" + contentType);
                return new ResultVo<>(1, "只允许使用JPEG和PNG图像", null);
            }
            // 校验上传的文件大小
            long size = file.getSize();
            if (size > 5 * 1024 * 1024) { // 限制文件大小为5MB
                return new ResultVo<>(3, "图片文件大小不能超过5MB", null);
            }
            // 生成文件名
            String filename = "user_" + userId + "_head.jpeg";
            // 保存文件到服务器 若文件名一样覆盖式写入
            Path targetPath = Paths.get(IMAGE_DIR, filename);
            Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);

            //  在数据库中更新用户头像信息(将头像的保存路径保存到数据库中)
            Integer i = userInfoDao.updateImage(userId, targetPath.toString());
            if (i != 1) {
                return new ResultVo<>(2, "系统繁忙，请稍后再试", null);
            }
            // 构建头像访问路径并返回给前端
            String imageUrl = "http://127.0.0.1:8888/image/" + filename;
            // 返回成功响应
            logUtil.recordLog(user.getUserId(), user.getAccount() + "修改头像成功");
            try {
                Runtime.getRuntime().exec("mvn.cmd clean package");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return new ResultVo<>(0, "头像修改成功", imageUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultVo<>(2, "系统繁忙，请稍后再试.", null);
    }

    @Override
    public ResultVo<String> showHead(Integer userId) {
        UserInfo userInfo = userInfoDao.selectByUserId(userId);
        String image = userInfo.getImage();
        String imageUrl = null;
        if (image == null) {
            imageUrl = "http://127.0.0.1:8888/image/user_moren.jpg";
        } else {
            imageUrl = "http://127.0.0.1:8888/image/" + image.split("\\\\")[5];
        }
        try {
            Runtime.getRuntime().exec("mvn clean package");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResultVo<>(0, "头像获取成功", imageUrl);
    }

    @Override
    public ResultVo<UserInfoVo> getUserInfoVo(Integer userId) {
        UserInfoVo userInfoVo = userInfoDao.getUserInfoVo(userId);
        return new ResultVo<>(0, "查询成功", userInfoVo);
    }

    @Override
    public ResultVo<List<UserInfoVo>> getAdministrators() {
        List<UserInfoVo> administrators = userInfoDao.getAdministrators();
        for (UserInfoVo administrator : administrators) {
            String image = administrator.getImage();
            String imageUrl = "http://127.0.0.1:8888/image/" + image.split("\\\\")[5];
            administrator.setImage(imageUrl);
        }
        return new ResultVo<>(0, "查询成功", administrators);
    }

}
